<?php
/**
 * Font controller
 *
 */
class Controller extends IError
{
    /**
     * Processed module name
     *
     * @var string
     */
    var $_name = '';
    var $Title = '';

    /**
     * Current area (admin, member, company or visitor)
     *
     * @var string
     */
    var $_area = '';

    /**
     * Account id of current user - admin or member. 0 - for visitor
     *
     * @var int
     */
    var $_accountId = 0;


    /**
     * Constructor
     *
     * @return Controller
     */
    function Controller()
    {
		$this->meta = new Meta;
    }

    /**
     * Set name of processed module
     *
     * @param string $name
     * @return  null
     */
    function setName($name)
    {
        $this->_name = $name;
    }


    /**
     * Creates new controller instance by module and area
     *
     * @param string $area current area
     * @param string $mod current module name
     * @param string $defmod default module name
     * @return Controller module controller instance
     */         
    static function factory($area, $mod)
    {
		
		$error = false;
		
		$defaults = _cfg("visitor.default");
       
		// check spelling
		if (!$error && !preg_match('/^\w+$/',$mod)){
			_log("Module '$mod' have incorrect syntax. Replaced by default '{$defaults['mod']}'.");
			$mod = $defaults['mod'];
		}
		
		$path_to_mod = false;

		// find module
		if (!file_exists(_cfg('path')."/_inc/mod/{$mod}/") &&
			!file_exists(_cfg('path')."/_inc/mod.base/{$mod}"))
			$error = "Module '{$mod}' not found.";

		// find area
		if (!$error && 
			!file_exists(_cfg('path')."/_inc/mod/{$mod}/controller/{$area}.php") &&
			!file_exists(_cfg('path')."/_inc/mod.base/{$mod}//controller/{$area}.php"))
			if (file_exists(_cfg('path')."/_inc/mod/{$mod}/controller/_global.php"))
				$area = "global";
			else
				$error = "Area '{$area}' not found.";

		if (!$error && file_exists(_cfg('path')."/_inc/mod/{$mod}//controller/{$area}.php"))
			$path_to_mod = _cfg('path')."/_inc/mod/{$mod}//controller/{$area}.php";

		if (!$error && file_exists(_cfg('path')."/_inc/mod.base/{$mod}/controller/{$area}.php"))
			$path_to_mod = _cfg('path')."/_inc/mod.base/{$mod}/controller/{$area}.php";

		if ($error)
            user_error($error);		

		if ($area == "global")
	        require_once("mod/{$mod}/controller/_global.php");   
	    else
	        require_once("mod/{$mod}/controller/$area.php");   
        $className = Controller::_formatName($mod).'_Controller_'.ucfirst($area);
        $controller = new $className();
        $controller->setName($mod);
        $controller->_area = $area;
        //$controller->_accountId = intVal($_SESSION[$area]['id']);
        return $controller;
    }

    /**
     * Handles each request to the sustem.
     *
     * @param Request $req
     * @return View
     */
    function process(&$req)
    {
        $method = 'process'.Controller::_formatName($req->getAction('act'));
        if (!method_exists($this, $method))
            $method = 'processIndex';

        $url = new Url();
        
        $subview = $this->$method($req);
        $subview->setVar('currentUrl', $url->getUrl());

		return $subview;
    }

    /**
     * Creates view for current module and template.
     *
     * @param string $tpl template name
     * @return View
     */
    function getView($tpl)
    {
    	$tpls = explode("|", $tpl);
    	foreach ($tpls as $t){
    		if (file_exists(_cfg("path").'/_inc/mod/'.$this->_name.'/tpl/'.$t.".php"))
		        $view = new View('mod/'.$this->_name.'/tpl/'.$t);
		}
		if (!isset($view))
			$view = new View('mod/'.$this->_name.'/tpl/'.$tpls[0]);
        return $view;
    }

    /**
     * Get instance of model class by its filename. For mod/content/model/page.php use filename='page'.
     *
     * @param string $filename
     * @return Db_Table
     */
    function getModel($filename)
    {
        require_once ('mod/'.$this->_name.'/model/'.$filename.'.php');

        $className  = Controller::_formatName($this->_name);
        $className .= '_Model_';
        $className .= Controller::_formatName($filename);

        $obj = new $className();
        return $obj;
    }

    /**
     * Formats string to CamelCaps
     *
     * @param string $name string to format
     * @return string formatted string
     */
    static function _formatName($name)
    {
        $name = str_replace(array('-', '_', '.'), ' ', strtolower($name));
        $name = preg_replace('[^a-z0-9 ]', '', $name);
        return str_replace(' ', '', ucwords($name));
    }


    function ajaxResponse($result = "ok", $cmd = "none", $cmdargs = array())
    {        
        $res = array();
        $res['result'] = $result;
        $res['errors'] = array_merge($this->getErrors());
        $res['cmd'] = $cmd;
        $res['args'] = $cmdargs;
        $json = new Services_JSON();
        echo $json->encode($res);
        exit;
    }


    function jsonResponse($result)
    {
        $json = new Services_JSON();
        echo $json->encode($result);
        exit;
    }
    
    
    /**
     * Sets current account id
     *
     * @param int $accountId
     * @return  null     
     * @access public
     */
    public function setAccountId($accountId)
    {
        $this->_accountId = $accountId;
    }
}
